package com.action;

import com.bean.ResponseBean;
import com.config.NoLogin;
import com.pojo.Admin;
import com.service.AdminService;
import com.util.IPUtil;
import com.util.JwtUtil;
import com.util.PasswordUtil;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminAction {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 管理员登录
     * @param username 用户名
     * @param password 密码
     * @param request
     * @return
     */
    @NoLogin
    @RequestMapping("/adminLogin")
    public ResponseBean adminLogin(String username, String password, HttpServletRequest request) {

        //获取ip
        String ip = IPUtil.getIpAddr(request);

        //从redis里取登录失败次数
        BoundValueOperations b = redisTemplate.boundValueOps(ip);
        if ("-1".equals(b.get())) {
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        if (!redisTemplate.hasKey(ip)) {
            b.set("1");
            b.expire(60, TimeUnit.SECONDS);
            //登录失败次数小于十，次数加一
        } else if (Integer.parseInt(b.get().toString()) < 10) {
            int tmp = Integer.parseInt(b.get().toString());
            b.set(String.valueOf(++tmp));
            b.expire(60, TimeUnit.SECONDS);
            //大于十，参数为-1,并一分钟内禁止登录
        } else {
            b.set("-1");
            b.expire(60, TimeUnit.SECONDS);
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        String pwd = PasswordUtil.jiami(password);
        Admin admin = adminService.login(username, pwd);

        if (admin != null && admin.getStatus() == 1) {
            Map map = new HashMap();
            map.put("token", JwtUtil.generToken(admin.getId(), null, null));
            map.put("username", admin.getUsername());
            map.put("id", admin.getId());
            return new ResponseBean(200,"登录成功",map);
        }
        if (admin == null) {
            return ResponseBean.error("用户名或密码错误");
        }
        return ResponseBean.error("用户已禁用");
    }

    /**
     * 校验是否登录
     */
    @NoLogin
    @RequestMapping("/verifyLogin")
    public ResponseBean verifyLogin(@RequestHeader(value = "token" , required = false) String token){
        String msg = adminService.verifyToken(token);
        if (StringUtil.isNotNull(msg)){
            return ResponseBean.error(msg);
        }
        String uid = JwtUtil.getUsername(token);
        Admin admin = adminService.getById(uid);
        if(admin == null){
            return ResponseBean.error("请先登录！");
        }else{
            return new ResponseBean(200,"已登录！",admin.getUsername());
        }
    }

    /**
     * 管理员修改密码
     * @param oldPwd
     * @param newPwd
     * @param request
     * @return
     */
    @RequestMapping("/updatePassword")
    public ResponseBean updatePassword(String oldPwd , String newPwd , HttpServletRequest request){
        Admin wuye = (Admin) request.getSession().getAttribute("admin") ;

        if(StringUtil.isNull(oldPwd)) {
            return ResponseBean.error("请输入旧密码") ;
        }
        if(StringUtil.isNull(newPwd)) {
            return ResponseBean.error("请输入新密码") ;
        }
        String res = adminService.wyUpdatePassword(oldPwd , newPwd , wuye.getId()) ;

        return res == null ? ResponseBean.OK : ResponseBean.error(res) ;
    }
}